package com.ftrend.printdemo.common

import android.content.Context
import com.loopstack.gprint.io.PortManager
import com.loopstack.gprint.io.PrinterDevices
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

object PrinterEthernet {


    public var portManager: PortManager? = null

    fun getConnectState():Boolean{
        portManager?.let {
            return it.getConnectStatus()
        }
        return false
    }

    //标签机是否连接
   fun isTicketConnect():Boolean{
        portManager?.let {
            if (it.getConnectStatus()&&it.getCommand()== com.loopstack.gprint.utils.Command.ESC){
                return true
            }else{
                return false
            }
        }
        return false
    }

    /**
     * 关闭连接
     * @return
     */
    fun close(){
       portManager?.let {
            it.closePort()
       }
       portManager = null
            //printer=null;
    }

    /**
     * 连接
     * @param devices
     */
    fun connect(devices: PrinterDevices, context: Context){
        MainScope().launch {
            withContext(Dispatchers.IO){
                portManager?.let {
                    it.closePort()
                }
                try {
                    devices?.let {
                        when(devices.getConnMethod()){
                            com.loopstack.gprint.utils.ConnMethod.WIFI ->{
                                portManager =
                                    com.loopstack.gprint.io.EthernetPort(devices);
                                portManager?.let {
                                    it.openPort()
                                }
                            }
                            else -> {

                            }
                        }
                    }
                }catch (e:Exception){

                }
            }
        }
    }


}